package com.saoft.dbinfo.updates;

import com.saoft.dbinfo.po.TableField;
import com.saoft.dbinfo.po.TableInfo;
import java.util.List;

public class H2Update extends AbstractDbUpdate{
    @Override
    public String createTable(TableInfo tableInfo) {
        StringBuffer buffer = new StringBuffer();
        String createTable = "CREATE TABLE `" + tableInfo.getName()+"`";
        buffer.append(createTable);
        buffer.append("(");
        List<TableField> fields = tableInfo.getFields();
        for (int i = 0; i < fields.size(); i++) {
            TableField field = fields.get(i);
            String sql = " `"+ field.getName() + "` " + field.getType();
            if(field.isKeyIdentityFlag()){
                sql += "AUTO_INCREMENT PRIMARY KEY";
            }

            if (i < fields.size() - 1) {
                sql += ",";
            }
            buffer.append(sql);
        }
        buffer.append(");");
        for (int i = 0; i < fields.size(); i++) {
            TableField field = fields.get(i);
            if (field.getComment() != null) {
                buffer.append("COMMENT ON COLUMN `" + tableInfo.getName() + "`.`" + field.getName() + "` IS '" + field.getComment() + "';");
            }
        }
        if (tableInfo.getComment() != null) {
            buffer.append("COMMENT ON TABLE `"+tableInfo.getName()+"` IS '"+tableInfo.getComment()+"';");
        }

        return buffer.toString();
    }
}
